package com.metadata_system.common.db.mapper;

import com.metadata_system.common.db.entity.MetadataNode;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

public interface MetadataNodeMapper extends Mapper<MetadataNode> {
    @Select("select last_insert_id()")
    int getLastInsertId();

    @Select("delete from md_metadata_node where metadata_id=#{id}")
    void deleteByMetadataId(@Param("id") Integer id);

    @Select("select id from md_metadata_node where metadata_id=#{id}")
    List<Integer> getIdsByMetadataId(@Param("id") Integer id);

    @Select("delete from md_metadata_node where metadata_view_id=#{id}")
    void deleteByViewId(@Param("id") Integer id);

    @Select("select id from md_metadata_node where metadata_view_id=#{id}")
    List<Integer> getIdsByViewId(@Param("id") Integer id);

    @Update("update md_metadata_node set data_total=#{dataTotal} where name=#{name} and metadata_id=#{metadataId}")
    void updateSetTotalByName(@Param("metadataId") Integer metadataId,@Param("name") String name,@Param("dataTotal") Integer dataTotal);

    /**
     * 删除多个节点
     * @param idList
     * @param metadataViewId
     */
    void deleteByIdList(@Param("idList") List<Integer> idList, @Param("metadataViewId") Integer metadataViewId);

    @Select("SELECT " +
            "    id," +
            "    name," +
            "    metadata_view_id AS metadataViewId," +
            "    metadata_id AS metadataId," +
            "    unique_key AS uniqueKey," +
            "    properties " +
            "FROM md_metadata_node " +
            "WHERE is_main=1 " +
            "GROUP BY " +
            "    CASE " +
            "        WHEN unique_key IS NOT NULL AND unique_key != '' THEN unique_key" +
            "        ELSE id " +
            "    END")
    List<MetadataNode> selectDistinctByUniqueKey();


    @Select("SELECT " +
            "    id," +
            "    name," +
            "    position," +
            "    metadata_view_id AS metadataViewId," +
            "    metadata_id AS metadataId," +
            "    unique_key AS uniqueKey," +
            "    properties_key AS propertiesKey," +
            "    properties " +
            " FROM md_metadata_node " +
            " WHERE metadata_id = #{metadataId} and is_main=1 " +
            "GROUP BY " +
            "    CASE " +
            "        WHEN unique_key IS NOT NULL AND unique_key != '' THEN unique_key" +
            "        ELSE id " +
            "    END")
    List<MetadataNode> selectDistinctByUniqueKeyByMetadataId(@Param("metadataId") Integer metadataId);

    @Select("select ifnull(sum(data_total),0) from md_metadata_node where metadata_id=#{metadataId}")
    Integer getDataTotalByMetadataId(Integer metadataId);
}